<?php

/*敏感词过滤处理*/

namespace App\Tools;


use Illuminate\Support\Facades\DB;
use App\Datas\Pay;
use App\Tools\FunTool;
use Illuminate\Support\Facades\Log;


class Sensitive {

	//过滤敏感词

	public static function formatData($sPrompt, $sReplacement = '***', $userId = 0, $platform = 0) {
		// Log::info('sensitive_format-uuid'.$userId, [$sPrompt]);

		$deviceId = FunTool::getDeviceId();
		$iPlatform = FunTool::getPlatform();//1:ios 2:安卓

		if(2 == $iPlatform) {

			return $sPrompt;//安卓不过滤了

			$pay = new Pay();
			$isPayVip = $pay->getIsPayVip($userId, $deviceId);

			if($isPayVip) {
				//Log::info('sensitive_format-222'.$userId, [$isPayVip, $sPrompt]);
				return $sPrompt;
			} else {
				//Log::info('sensitive_format-333'.$userId, [$isPayVip, $sPrompt]);
			}
			//Log::info('sensitive_format-444'.$userId, [$isPayVip, $sPrompt]);
		}

		//$sReplacement = '';
		$sPrompt = preg_replace('!\s+!', ' ', $sPrompt);
		$sPrompt = str_replace('..', '.', $sPrompt);

		$sensitives = DB::table('sensitives')->get();
		$sensitives_arr = [];
		foreach($sensitives as $key => $value) {
			$sensitives_arr[$value->type][] = $value->data;
		}

		$aSW = $sensitives_arr[1] ?? config('thesaurus.a', []);
		if(!empty($aSW)) {
			uasort($aSW, function($A, $B) {
				return strlen($A) < strlen($B); //< 改为 > 就变成了升序排序
			});
			$sPattern = '/('.implode('|', $aSW).')/i'; // 构造正则表达式
			$sPrompt = preg_replace($sPattern, $sReplacement, $sPrompt);
		}

		$aSW = $sensitives_arr[2] ?? config('thesaurus.b', []);
		uasort($aSW, function($A, $B) {
			return strlen($A) < strlen($B); //< 改为 > 就变成了升序排序
		});
		$aString = explode(' ', $sPrompt);
		foreach($aString as &$sString) {
			$sString = self::_replaceSensitiveWord($sString, $aSW, $sReplacement);
		}
		$sPrompt = join(' ', $aString);


		/**
		 * 安卓：过滤儿童色情相关
		 * 苹果：过滤儿童色情相关，word词不过滤试用用户，过滤正式用户
		 */ //if(2 == $platform) {// 1:ios 2:安卓
		//	return $sPrompt;
		//}

		//if(empty($userId)) {
		//	return $sPrompt;
		//}

		$aSW = $sensitives_arr[3] ?? config('thesaurus.c', []);
		uasort($aSW, function($A, $B) {
			return strlen($A) < strlen($B); //< 改为 > 就变成了升序排序
		});
		$aString = explode(' ', $sPrompt);
		foreach($aString as &$sString) {
			$sString = self::_replaceSensitiveWord($sString, $aSW, $sReplacement);
		}
		return join(' ', $aString);
	}

	public static function _replaceSensitiveWord($sString, $aSensitiveWord, $sReplacement = '***') {
		$bIsEn = self::_isEn($sString);
		if(!empty($aSensitiveWord)) {
			foreach($aSensitiveWord as $sSensitiveWord) {
				if(true === $bIsEn) {
					//去除标点符号

					if(strtolower($sString) == $sSensitiveWord) {
						return $sReplacement;
					}
				} else {
					$sString = str_ireplace($sSensitiveWord, $sReplacement, $sString);
				}
			}
		}
		return $sString;
	}

	public static function _isEn($sKeyword) {
		$Res = preg_match('/^[A-Za-z0-9]+$/', $sKeyword);
		if($Res) {
			return true;
		} else {
			return false;
		}
	}


}
